package com.ssvendas.filtro;

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ssvendas.modelo.Usuario;
import com.ssvendas.util.Constants;

public class AutenticadorSessao implements Filter, Serializable {

	private static final long serialVersionUID = 8072680858090704425L;

	public AutenticadorSessao() {

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		Usuario usuario = (Usuario) ((HttpServletRequest) request).getSession()
				.getAttribute(Constants.USER);

		String url = ((HttpServletRequest) request).getRequestURL().toString();
		System.out.println("teste:" + url);

		if(usuario != null && url.contains("login")){
			String contextPath = ((HttpServletRequest) request).getContextPath();
			((HttpServletResponse) response).sendRedirect(contextPath+ "/sistema/index.jsf");
		}
		
		if (usuario == null && !url.contains("login")) {
			String contextPath = ((HttpServletRequest) request).getContextPath();
			((HttpServletResponse) response).sendRedirect(contextPath+ "/login.jsf");
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
